package team.knowers.qzh.qzhserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import team.knowers.qzh.qzhserver.common.convention.exception.ClientException;
import team.knowers.qzh.qzhserver.common.database.BaseDO;
import team.knowers.qzh.qzhserver.dao.entity.LikeVersionLogsDO;
import team.knowers.qzh.qzhserver.dao.entity.SectionDO;
import team.knowers.qzh.qzhserver.dao.mapper.LikeVersionLogsMapper;
import team.knowers.qzh.qzhserver.dto.req.VersionLikeReqDTO;
import team.knowers.qzh.qzhserver.service.LikeVersionLogsService;
import team.knowers.qzh.qzhserver.service.SectionService;

import java.sql.Wrapper;

/**
 * @author xtg
 */
@Service
@RequiredArgsConstructor
public class LikeVersionLogsServiceImpl extends ServiceImpl<LikeVersionLogsMapper, LikeVersionLogsDO> implements LikeVersionLogsService {
    private final SectionService service;

    /**
     * 为当前版本点赞
     */
    @Override
    public Boolean likeThisVersionSection(VersionLikeReqDTO reqDTO) {
        LambdaQueryWrapper<LikeVersionLogsDO> eq = Wrappers.lambdaQuery(LikeVersionLogsDO.class).eq(LikeVersionLogsDO::getUserId, reqDTO.getUserId()).eq(LikeVersionLogsDO::getSectionId, reqDTO.getSectionId()).eq(LikeVersionLogsDO::getDelFlag, 0);
        LikeVersionLogsDO likeVersionLogsDO = baseMapper.selectOne(eq);
        if (likeVersionLogsDO != null) {
            throw new ClientException("您已经点赞过该版本");
        }
        LikeVersionLogsDO build = LikeVersionLogsDO.
                builder().sectionId(reqDTO.getSectionId()).userId(reqDTO.getUserId()).build();
        baseMapper.insert(build);
        LambdaQueryWrapper<SectionDO> eq1 = Wrappers.lambdaQuery(SectionDO.class).eq(SectionDO::getId, reqDTO.getSectionId());
        SectionDO sectionDO = service.getBaseMapper().selectOne(eq1);
        sectionDO.setLikes(sectionDO.getLikes() + 1);
        LambdaUpdateWrapper<SectionDO> eq2 = Wrappers.lambdaUpdate(SectionDO.class).eq(SectionDO::getId, reqDTO.getSectionId());
        service.getBaseMapper().update(sectionDO, eq2);
        return true;
    }
}
